package com.longcai.piaojia.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.adapter.LatestDetailAdapter;
import com.longcai.piaojia.conn.Conn;
import com.longcai.piaojia.conn.LatestDetailGet;
import com.longcai.piaojia.conn.LatestDetailTopicGet;
import com.longcai.piaojia.conn.LatestOrderReplyGet;
import com.longcai.piaojia.dialog.EvaluateDialog;
import com.longcai.piaojia.dialog.WarnningDialog;
import com.longcai.piaojia.util.MyToast;
import com.longcai.piaojia.util.UtilPermission;
import com.longcai.piaojia.widget.NoScrollListView;
import com.module.pull.PullToRefreshBase;
import com.module.pull.PullToRefreshListView;
import com.module.pull.PullToRefreshScrollView;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.glide.GlideLoader;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;
import com.zcx.helper.util.UtilApp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by Administrator on 2017/1/9.
 */
public class LatestDetailActivity extends BaseActivity implements View.OnClickListener, LatestDetailAdapter.LatestDetailEvaluate {

    @BoundView(R.id.latest_detail_rl) private RelativeLayout latest_detail_rl;
    @BoundView(R.id.latest_detail_sv) private PullToRefreshScrollView pullToRefreshScrollView;
    private ScrollView latest_detail_sv;
    @BoundView(R.id.latest_detail_iv) private ImageView latest_detail_iv;
    @BoundView(R.id.latest_detail_time_tv) private TextView latest_detail_time_tv;
    @BoundView(R.id.latest_detail_address_tv) private TextView latest_detail_address_tv;
    @BoundView(R.id.latest_detial_call_rl) private RelativeLayout latest_detial_call_rl;
    @BoundView(R.id.latest_detail_rg) private RadioGroup latest_detail_rg;
    @BoundView(R.id.latest_detail_left_rb) private RadioButton latest_detail_left_rb;
    @BoundView(R.id.latest_detail_right_rb) private RadioButton latest_detail_right_rb;
    @BoundView(R.id.latest_detail_wv) private WebView latest_detail_wv;
    @BoundView(R.id.latest_detail_lv) private NoScrollListView latest_detail_lv;
    @BoundView(R.id.latest_detail_order_rl) private RelativeLayout latest_detail_order_rl;
    private List<LatestDetailTopicGet.MyEvalute> lists = new ArrayList<>();
    private LatestDetailAdapter adapter;
    private LatestDetailGet.LatestDetailEntity mLatestDetailEntity;
    private LatestDetailTopicGet.LatestTopicEntity mlatestTopicEntity;
    private Bundle bundle;

    private String url = "http://url.cn/44C3pDE";
    private Bitmap bitmap;
    private PopupWindow popupWindow;

    private LatestOrderReplyGet latestOrderReplyGet = new LatestOrderReplyGet(new AsyCallBack<String>() {

        @Override
        public void onSuccess(String toast, int type, String s) throws Exception {

            Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();

        }
    });


    private LatestDetailTopicGet latestDetailTopicGet = new LatestDetailTopicGet(new AsyCallBack<LatestDetailTopicGet.LatestTopicEntity>() {

        @Override
        public void onSuccess(String toast, int type, LatestDetailTopicGet.LatestTopicEntity latestTopicEntity) throws Exception {

            if (type != 1) {

                lists.clear();

            }

            mlatestTopicEntity = latestTopicEntity;

            lists.addAll(latestTopicEntity.myEvaluteList);

            adapter.notifyDataSetChanged();
        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onEnd(String toast, int type) throws Exception {

            setLastUpdateTime();

            pullToRefreshScrollView.onPullUpRefreshComplete();
            pullToRefreshScrollView.onPullDownRefreshComplete();
        }
    });

    private LatestDetailGet latestDetailGet = new LatestDetailGet(new AsyCallBack<LatestDetailGet.LatestDetailEntity>() {

        @Override
        public void onSuccess(String toast, int type, LatestDetailGet.LatestDetailEntity latestDetailEntity) throws Exception {

            mLatestDetailEntity = latestDetailEntity;

            GlideLoader.getInstance().get(context, latestDetailEntity.picarr, latest_detail_iv, R.mipmap.home_center);

            latest_detail_time_tv.setText(latestDetailEntity.starttime + "(" + latestDetailEntity.startweek + ")—" + latestDetailEntity.endtime + "(" + latestDetailEntity.endweek + ")");

            latest_detail_address_tv.setText(latestDetailEntity.address);

        }

        @Override
        public void onFail(String toast, int type) throws Exception {


        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_latest_detail);

        setBackTrue();

        View view = BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) getLayoutInflater().inflate(R.layout.latest_detail_content, null)));

        bundle = getIntent().getExtras();

        setTitleName(bundle.getString("title", ""));

        setLatestRightImage(this);

        String[] permission = { Manifest.permission.CALL_PHONE};
        UtilPermission.Permission(this, permission);

        pullToRefreshScrollView.setPullLoadEnabled(false);
        pullToRefreshScrollView.setPullRefreshEnabled(false);

        pullToRefreshScrollView.getRefreshableView().setVerticalScrollBarEnabled(false);

        pullToRefreshScrollView.getRefreshableView().addView(view);

        latest_detail_lv.setFocusable(false);

        latest_detail_lv.setAdapter(adapter = new LatestDetailAdapter(this, lists));

        latest_detail_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {

                    case R.id.latest_detail_left_rb:

                        latest_detail_wv.setVisibility(View.VISIBLE);
                        latest_detail_lv.setVisibility(View.GONE);

                        pullToRefreshScrollView.setPullLoadEnabled(false);
                        pullToRefreshScrollView.setPullRefreshEnabled(false);

                        break;

                    case R.id.latest_detail_right_rb:

                        latest_detail_wv.setVisibility(View.GONE);
                        latest_detail_lv.setVisibility(View.VISIBLE);

                        pullToRefreshScrollView.setPullLoadEnabled(true);
                        pullToRefreshScrollView.setPullRefreshEnabled(true);

                        break;

                }

            }
        });

        latest_detail_wv.loadUrl(Conn.SERVICE + Conn.ACTIVITY_WEB_VIEW + "?id=" + bundle.getString("id", ""));

        Log.e("url", Conn.SERVICE + Conn.ACTIVITY_WEB_VIEW + "?id=" + bundle.getString("id", ""));

        latestDetailGet.id = bundle.getString("id", "");
        latestDetailGet.execute(this);

        latestDetailTopicGet.page = 1;
        latestDetailTopicGet.id = bundle.getString("id", "");
        latestDetailTopicGet.execute(this);

        pullToRefreshScrollView.setPullLoadEnabled(true);
        pullToRefreshScrollView.setPullRefreshEnabled(true);
        pullToRefreshScrollView.setScrollLoadEnabled(false);


        pullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {

                Log.e("123123", "xiala");

                latestDetailTopicGet.page = 1;
                latestDetailTopicGet.id = bundle.getString("id", "");
                latestDetailTopicGet.execute(context, false);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

                Log.e("123123", "shangla");

                if (lists != null && lists.size() < mlatestTopicEntity.total) {

                    latestDetailTopicGet.page = mlatestTopicEntity.current_page + 1;
                    latestDetailTopicGet.id = bundle.getString("id", "");
                    latestDetailTopicGet.execute(context, false, 1);

                } else {

                    pullToRefreshScrollView.onPullUpRefreshComplete();
                    pullToRefreshScrollView.onPullDownRefreshComplete();
                }
            }
        });

        latest_detail_order_rl.setOnClickListener(this);
        latest_detial_call_rl.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.title_latest_right_ll:

                if (popupWindow == null) {
                    popupWindow = new PopupWindow(this);
                    popupWindow.setContentView(initView());
                    // PopupWindow必须设置高度和宽度
                    popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.popwindow_bg));
                    popupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT); // 设置宽度
                    popupWindow.setHeight(LinearLayout.LayoutParams.MATCH_PARENT); // 设置popWin 高度
                    popupWindow.showAtLocation(latest_detail_rl, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
                    popupWindow.setOutsideTouchable(true);// 设置后点击其他位置PopupWindow将消失
                } else if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    popupWindow.showAtLocation(latest_detail_rl, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
                }

                break;

            case R.id.latest_detail_order_rl:

                if (!BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(this, LoginActivity.class));

                } else {

                    startActivity(new Intent(this, LatestOrderActivity.class).putExtras(bundle));

                }

                break;

            case R.id.latest_detial_call_rl:

                new WarnningDialog(context, mLatestDetailEntity.mobile, context.getString(R.string.cancel_text), context.getString(R.string.confirm_text)) {
                    @Override
                    protected void onConfirm() {

                        UtilApp.call(context, mLatestDetailEntity.mobile);

                        return;
                    }
                }.show();

                break;
        }
    }


    @Override
    public void clickEvaluate(final int pos) {

        if (!BaseApplication.BasePreferences.readIsLogin()) {

            startActivity(new Intent(this, LoginActivity.class));

        } else {

            new EvaluateDialog(context) {
                @Override
                protected void onConfirm(String content) {

                    if (!TextUtils.isEmpty(content)) {

                        latestOrderReplyGet.id = lists.get(pos).id;
                        latestOrderReplyGet.content = content;
                        latestOrderReplyGet.user_id = BaseApplication.BasePreferences.readUserId();
                        latestOrderReplyGet.p_id = lists.get(pos).p_id;

                        latestOrderReplyGet.execute(LatestDetailActivity.this);
                    }

                }
            };

        }


    }

    private void setLastUpdateTime() {

        SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");

        String text = mDateFormat.format(System.currentTimeMillis());

        pullToRefreshScrollView.setLastUpdatedLabel(text);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (bitmap!=null) {

            bitmap.recycle();

            bitmap = null;
        }

    }

    private View initView(){

        View view = View.inflate(this, R.layout.popwindow_my_setting_share, null);
        ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) view);
        RelativeLayout popwindow_main_rl = (RelativeLayout) view.findViewById(R.id.popwindow_main_rl);
        RelativeLayout my_setting_share_friend_rl = (RelativeLayout) view.findViewById(R.id.my_setting_share_friend_rl);
        RelativeLayout my_setting_share_pengyouquan_rl = (RelativeLayout) view.findViewById(R.id.my_setting_share_pengyouquan_rl);

        my_setting_share_friend_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popupWindow.dismiss();
                showShare(LatestDetailActivity.this, 1);

            }
        });

        my_setting_share_pengyouquan_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popupWindow.dismiss();
                showShare(LatestDetailActivity.this, 2);

            }
        });

        popwindow_main_rl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                popupWindow.dismiss();

                return false;
            }
        });
        return view;

    }

    public void showShare(final Context context, int type) {

        Resources res = context.getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, R.mipmap.share_icon);

        if(type==1){

            Wechat.ShareParams shareParams = new Wechat.ShareParams();
            shareParams.shareType = Platform.SHARE_WEBPAGE;

//            shareParams.setText(share_time + "\n" + share_address);

            shareParams.setText("“小橙堡欢乐寒假运动季”赏冰乐雪园");
            shareParams.setTitle("友票会员免费玩!");

            shareParams.setImageData(bmp);

//            http://api.heiyoupiao.com/index.php/web/reg/index

            shareParams.setUrl(url);

            Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
            wechat.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_success_text));

                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_failed_text));

                }

                @Override
                public void onCancel(Platform platform, int i) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_failed_text));

                }
            });

            wechat.share(shareParams);

        }else{

            WechatMoments.ShareParams shareParams = new WechatMoments.ShareParams();
            shareParams.shareType = Platform.SHARE_WEBPAGE;

//            shareParams.setText(share_time + "\n" + share_address);

            shareParams.setText("“小橙堡欢乐寒假运动季”赏冰乐雪园");
            shareParams.setTitle("友票会员免费玩!");

            shareParams.setImageData(bmp);

            shareParams.setUrl(url);

            Platform wechatmoents = ShareSDK.getPlatform (WechatMoments.NAME);
            wechatmoents.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_success_text));

                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_failed_text));

                }

                @Override
                public void onCancel(Platform platform, int i) {

//                    UtilToast.show(context, context.getString(R.string.goods_info_share_failed_text));

                }
            });

            wechatmoents.share(shareParams);

        }

    }

}
